import { FC, useEffect } from "react";
import { UsergroupAddOutlined } from "@ant-design/icons";
import { Form, Input, Button, Checkbox } from "antd";
import { Link } from "react-router-dom";
import { LOGIN_PATHNAME } from "../router";

const NAME_KEY = "username";
const PWD_KEY = "pwd";

function savePwd(username: string, pwd: string) {
  localStorage.setItem(NAME_KEY, username);
  localStorage.setItem(PWD_KEY, pwd);
}

function delPwd() {
  localStorage.removeItem(NAME_KEY);
  localStorage.removeItem(PWD_KEY);
}

function getPwd() {
  return {
    username: localStorage.getItem(NAME_KEY),
    pwd: localStorage.getItem(PWD_KEY),
  };
}

const Login: FC = () => {
  const [form] = Form.useForm();

  useEffect(() => {
    const { username, pwd } = getPwd();
    form.setFieldsValue({ username, pwd });
  });

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const onFinish = (values: any) => {
    console.log("Success:", values);
    const { remember, username, pwd } = values!;
    if (remember) {
      savePwd(username, pwd);
    } else {
      delPwd();
    }
  };

  return (
    <div className="h-full flex items-center justify-center">
      <div className="w-[260px]">
        <h2 className="font-bold text-center">
          <UsergroupAddOutlined className="text-2xl mr-1" />
          用户登录
        </h2>
        <Form
          form={form}
          labelCol={{ span: 6 }}
          onFinish={onFinish}
          initialValues={{ remember: true }}
        >
          <Form.Item
            label="用户名："
            name="username"
            rules={[
              { required: true, message: "请输入用户名" },
              { type: "string", min: 5, max: 20, message: "字符在5-20之间" },
              { pattern: /^\w+$/, message: "只能是字母数字下划线" },
            ]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item label="密码：" name="pwd" rules={[{ required: true, message: "请输入密码" }]}>
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
          <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 6 }}>
            <Checkbox>记住我</Checkbox>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 6 }}>
            <Button type="primary" htmlType="submit">
              登录
            </Button>
            <Link className="ml-2" to={LOGIN_PATHNAME}>
              已有账号，登录
            </Link>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
